// pages/addPhoto/addPhoto.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    httpApiImg: app.globalData.httpApiImg,
    img: [],
    formData:{
      img:''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var img = wx.getStorageSync('img');
    if(img){
      this.setData({
        img: img.split(","),
        ['formData.img']: img
      })
    }
  },
  back: function(){
    wx.navigateBack();
    wx.setStorageSync("img", this.data.formData.img);
  },
  // 添加图片
  addPhoto: function (e) {
    var that = this,
      count = 0,
      key = e.currentTarget.dataset.id,
      only = e.currentTarget.dataset.only;
    only ? count = 1 : count = 9 - this.data[key].length;
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var imgsrc = res.tempFilePaths;
        that.uploadImg(imgsrc, key, 0)
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  /*上传图片*/
  uploadImg: function (path, key, tag, oIndex) {
    var data1 = app.uploadimg({
      url: app.globalData.httpApiCar + 'uploadfile/upload1',
      path: path,
      globalkey: this,
      realpath: this.data[key],
      showkey: key,
      key: 'formData.' + key,
      tag: tag,
      oIndex: oIndex
    });
  },
  // 修改图片
  changePhoto: function (e) {
    var that = this,
      key = e.currentTarget.dataset.id,
      index = e.currentTarget.dataset.value;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var imgsrc = res.tempFilePaths;
        that.uploadImg(imgsrc, key, 1, index)
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  delImg: function (e) {
    var key = e.currentTarget.dataset.id,
      index = e.currentTarget.dataset.value;
    this.data[key].splice(index, 1);
    this.setData({
      [key]: this.data[key],
      ['formData.' + key]: this.data[key].join(",")
    });

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})